package com.traitswu.websocket.dmxlog;

import com.traitswu.websocket.dmxlog.core.DmxLogEndpoint;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.HashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * Created by xiaoquan on 17-5-27.
 */


@WebListener
public class MyServletContextListener implements ServletContextListener {
    private ScheduledFuture<?> future;

    private ScheduledExecutorService scriptSchedule = Executors.newSingleThreadScheduledExecutor();

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        future = scriptSchedule.scheduleWithFixedDelay(() -> {
            try {
                ScriptExecuteUtils.eval("action1", new HashMap<>());
                ScriptExecuteUtils.eval("action2", new HashMap<>());

            } catch (Exception e) {

            }
        }, 5, 5 , TimeUnit.SECONDS);

        System.out.println("MyServletContextListener init");

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

        if (future != null) {
            future.cancel(true);
        }
        scriptSchedule.shutdown();
        System.out.println("MyServletContextListener destory");
        DmxLogEndpoint.pingPongTest.shutdown();

    }
}
